<template>
  <div class='article_list_container'>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" :immediate-check="false"
        offset="50">
        <AricleItem v-for="item in articleList" :key="item.art_id" :artObj="item" @dislikeEV="dislikeFn"
          @reportEV="reportFn" @click.native="itemClickFn(item.art_id)"></AricleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import AricleItem from '../../../components/ArticleItem.vue'
import { getAllArticleListAPI, artDislikeAPI, artRepostAPI } from '@/api/index'
import { Notify } from 'vant'

export default {
  name: 'MyArticleList',
  props: ['channelId'],
  data () {
    return {
      articleList: [],
      loading: false,
      finished: false,
      theTime: new Date().getTime(),
      isLoading: false
    }
  },
  components: {
    AricleItem
  },
  methods: {
    // 1.获取文章列表
    async getAllArticleList () {
      const { data: res } = await getAllArticleListAPI({ channel_id: this.channelId, timestamp: this.theTime })
      if (res.message === 'OK') {
        // 合并数组
        this.articleList = [...this.articleList, ...res.data.results]
        // 更新上一次事件
        this.theTime = res.data.pre_timestamp
      } else {
        return Notify({ type: 'danger', message: '获取文章列表失败' })
      }
      this.loading = false
      if (res.data.pre_timestamp === null) {
        this.finished = true
      }
      this.isLoading = false
    },

    // 2.底部加载事件方法
    async onLoad () {
      if (this.articleList.length === 0) {
        this.loading = false
        return
      }
      this.getAllArticleList()
    },

    // 3.下拉刷新事件
    async onRefresh () {
      this.articleList = []
      this.theTime = new Date().getTime()
      this.getAllArticleList()
    },

    // 4.子组件点击不喜欢触发父类的事件
    async dislikeFn (id) {
      try {
        const { data: res } = await artDislikeAPI({ artId: id })
        if (res.message === 'OK') {
          return Notify({ type: 'success', message: '反馈成功' })
        } else {
          return Notify({ type: 'danger', message: '反馈失败' })
        }
      } catch (err) { }
    },

    // 5.子组件点击反馈时触发父类的事件
    async reportFn (id, type) {
      try {
        const { data: res } = await artRepostAPI({ artId: id, type })
        if (res.message === 'OK') {
          return Notify({ type: 'success', message: '举报成功' })
        } else {
          return Notify({ type: 'danger', message: '举报失败' })
        }
      } catch (err) { }
    },

    // 6.点击文章单元格
    itemClickFn (artId) {
      this.$router.push({
        path: '/article-detail',
        query: {
          artId
        }
      })
    }
  },
  created () {
    this.getAllArticleList()
  },
  mounted () { }
}
</script>

<style lang='less' scoped>

</style>
